
package chart5;

import java.util.ArrayList;
import java.util.Date;


/*
 * 
 * Class carriyng the data and working with the chart class.
 * 
 */

public class DataSet {
    
private ArrayList<Point> array;    
private int array_capacity;
private Date start_date;
private Date finish_date;
private Double time_per_point;


/*
 * @return number in array of point with this date
 * @param  date of the measuring
 */

private int dateToNumber( Date date )
{
   int  a = (int)((date.getTime() - start_date.getTime())/time_per_point);
   if (a >= array_capacity) a--;
   return a;
 };


private Date numberToDate(int number)
{
    return new Date( start_date.getTime() + (long)(number*time_per_point) );
    
};


/*
 *
 * @param start and finifh of the measuring
 */

DataSet(Date start, Date finish)
 {

    // To make app more flexible you can write another constructor with not standart array_capacity

    array_capacity = 100;

    start_date = start;
    finish_date = finish;
    time_per_point = (finish_date.getTime() - start_date.getTime()) / 1.0 / array_capacity ;
   // System.out.print("DataSet start time"+ start.toString()+" "+finish.toString()+time_per_point.toString());

    array = new ArrayList<Point>(array_capacity);
    
    for (int i = 0; i < array_capacity; ++i )
    {
        array.add(i, new Point( numberToDate(i) ));
    }

 };


 /*
  *
  * @param measur
  */

 public void addRecord( Date date, Long func )
{

    //System.out.print("\n"+date.toString()+" "+func.toString()+" point number ");

   int point_number = dateToNumber(date);

   // System.out.print(point_number);

    Point point = (Point) (array.get(point_number));
  
    if (point.witness == 0)
    {
        point.witness = 1;
        point.max = func;
        point.min = func;
        point.aver = (double) (func);
        
    }
    else
    {
        if (point.max < func) point.max = func;
        if (point.min > func) point.min = func;
        point.aver = (point.aver * point.witness + func) / (point.witness+1);
        point.witness++;
    }
    
 };

 
 /*
  * 
  * 
  * Just for logging and debugging
  * 
  */
 
 public void printData()
 {
      for (int i = 0; i < array_capacity; ++i )
    {
       Point p = array.get(i);
      // System.out.print("\n"+p.date.toString()+" "+Integer.toString(p.witness)+" "+ Double.toString(p.aver));
    }
 };


 /*
  *
  * After we've stored all data we can make a chart
  *
  */


 public void makeChart()
 {
     ChartPrinter chart = new ChartPrinter("Yandex");

    for (int i = 0; i < array_capacity; ++i )
    {
       Point point = array.get(i);
       chart.add(point.date, point.aver);
    }
     chart.print();
 };

}
